const router = require("express").Router();
const { ScreeningRoom} = require('@/models')
const expressJoi = require('@escook/express-joi')
const { data } = require('@/utils/send')
const { add, put, del } = require('@/joi/room')
router.get('/', async (req, res) => {
    try {
        const { page = 1, size = 10, id } = req.query
        const where = { is_delete: 0 }
        const order = [['id', 'desc']]
        const limit = Number(size)
        const offset = (Number(page) - 1) * limit
        const query = id ? ScreeningRoom.findOne({ where: { id } }) : ScreeningRoom.findAndCountAll({ where, order, limit, offset })
        const cinema = await query
        if (!cinema) return res.cc('获取放映厅信息失败')
        const message = id ? '获取放映厅信息成功' : '获取放映厅列表成功'
        const datas = data({ message, data: cinema })
        res.send(datas)
        res.locals.data = datas;
    } catch (error) {
        res.cc(error)
    }
})
router.post('/', expressJoi(add), async (req, res) => {
    try {
        const info = await ScreeningRoom.create({ ...req.body })
        if (!info) return res.cc('添加失败')
        const datas = data({ message: '添加放映厅成功' })
        res.send(datas)
        res.locals.data = datas;
    } catch (error) {
        res.cc(error)
    }
})
router.put('/', expressJoi(put), async (req, res) => {
    try {
        const { id } = req.body
        const cinema = await ScreeningRoom.findOne({
            where: { id }
        })
        if (!cinema) return res.cc('该放映厅不存在')
        const result = await cinema.update(req.body)
        if (!result) return res.cc('修改失败')
        const datas = data({ message: '修改放映厅成功' })
        res.send(datas)
        res.locals.data = datas;
    } catch (error) {
        res.cc(error)
    }
})
router.delete('/', expressJoi(del), async (req, res) => {
    try {
        let { id } = req.query
        id = Number(id)
        console.log(id);
        const cinema = await ScreeningRoom.findOne({
            where: { id }
        })
        if (!cinema) return res.cc('该放映厅不存在')
        const result = await cinema.update({ is_delete: 1 })
        if (!result) return res.cc('删除失败')
        const datas = data({ message: '删除放映厅成功' })
        res.send(datas)
        res.locals.data = datas;
    } catch (error) {
        res.cc(error)
    }
})

module.exports = router
